package com.gnerv.tools.entity.extend.utils.mapper;

import com.gnerv.tools.entity.extend.annotation.EntityExtend;
import com.gnerv.tools.entity.extend.utils.NameUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ResultMapUtils {

    public final static String EXTEND_MAP = ".EntityExtendMap";

    private ResultMapUtils() {
    }

    public static List<ResultMap> buildResultMap(MappedStatement ms, Set<EntityExtend> entityExtends) {
        List<ResultMap> lists = new ArrayList<>(10);
        ResultMap resultMap = ms.getResultMaps().get(0);
//        List<ResultMapping> resultMappings = ResultMappingUtils.buildResultMapping(ms, entityExtends);
        List<ResultMapping> resultMappings = ResultMappingUtils.buildMapResultMapping(ms, Object.class);
        ResultMap build = new ResultMap.Builder(ms.getConfiguration(), resultMap.getId(), resultMap.getType(), resultMappings).build();
        lists.add(build);
        return lists;
    }

    public static ResultMap buildExtendResultMap(MappedStatement ms, Set<EntityExtend> entityExtends) {
        List<ResultMapping> resultMappings = new ArrayList<>(10);
        for (EntityExtend entityExtend : entityExtends) {
            List<ResultMapping> composites = CompositesUtils.buildExtendComposites(ms, entityExtend);
            ResultMapping resultMapping =
                    new ResultMapping.Builder(ms.getConfiguration(), NameUtils.lowerCamelCase(entityExtend), entityExtend.column(), entityExtend.resultType())
                            .nestedQueryId(entityExtend.selectMethod())
                            .composites(composites)
                            .build();
            resultMappings.add(resultMapping);
        }
        ResultMap build = new ResultMap.Builder(ms.getConfiguration(), buildExtendResultMapId(ms), Map.class, resultMappings).build();
        return build;
    }

    public static String buildExtendResultMapId(MappedStatement ms) {
        String msId = ms.getId();
        String substring = msId.substring(0, msId.lastIndexOf("."));
        return substring + EXTEND_MAP;
    }
}
